package com.example.jdbc.config;

import com.example.jdbc.bean.LearnResource;
import com.example.jdbc.bean.User;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import com.example.jdbc.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.apache.shiro.authc.AccountException;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Component
public class MyShrioRealm  extends AuthorizingRealm{

    Logger log= LoggerFactory.getLogger(MyShrioRealm.class);
    @Resource
    private UserService UserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
           log.info("用户权限验证");
           String username= (String) principalCollection.getPrimaryPrincipal();
           if("嘟嘟".equalsIgnoreCase(username)){
               SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
               Set<String> permissionSet=new HashSet<String>();
               permissionSet.add("add");
               info.setStringPermissions(permissionSet);
               return  info;
           }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       log.info("用户身份验证");
        UsernamePasswordToken authToken=(UsernamePasswordToken)authenticationToken;
        String username=(String) authToken.getUsername();
        User user=UserService.queryUserByName(username);
        if(user==null){
            throw  new AccountException("账号或者密码不正确");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,user.getAge()+"",getName());
        return info;
    }
}
